package com.lz.function;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * redis分布式锁
 * Created by Administrator on 2018/9/7 0007.
 */
@Slf4j
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 加锁
     * @param key 商品id
     * @param value 当前时间+过期时间
     * @return
     */
    public boolean lock(String key,String value){
        if (stringRedisTemplate.opsForValue().setIfAbsent(key,value)){
            return true;
        }
        String current = stringRedisTemplate.opsForValue().get(key);
        //如果锁过期
        if (!StringUtils.isEmpty(current) && Long.parseLong(current) < System.currentTimeMillis()){
            //获取上一个锁的时间
            String oldValue = stringRedisTemplate.opsForValue().getAndSet(key, value);
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(current)){
                return true;
            }
        }

        return false;
    }

    /**
     * redis解锁
     * @param key
     * @param value
     */
    public void unlock(String key,String value){
        try {
            String current = stringRedisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(current) && current.equals(value)){
                stringRedisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            log.error("【redis分布式锁】解锁异常{}",e);
        }
    }
}
